/**   
* @{#} Order.java Create on 2013-6-22 下午10:01:18   
*   
* Copyright (c) 2012 by Baidu.   
*/
package objtable.algm;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import objtable.struct.Row;

/**   
* @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>  
* @version 1.0   
*/

public class OrderBy implements Algm1Row {
	private String[] fields;
	private boolean ascflag;

	public OrderBy(String orderfields, boolean asc) {
		fields = orderfields.split(",");
		ascflag = asc;
	}

	private Comparator<Row> genComparator(final String[] sortfields,
			final boolean asc) {
		Comparator<Row> comp;
		comp = new Comparator<Row>() {
			@SuppressWarnings({ "rawtypes", "unchecked" })
			public int compare(Row o1, Row o2) {
				for (String s : sortfields) {
					Comparable c1 = (Comparable) o1.get(s);
					Comparable c2 = (Comparable) o2.get(s);
					int k = c1.compareTo(c2);
					if (k != 0) {
						return asc ? k : -k;
					}
				}

				return 0;
			}
		};
		return comp;
	}

	public List<? extends Row> execute(List<? extends Row> rows) {
		Collections.sort(rows, genComparator(fields, ascflag));
		return rows;
	}
}
